<template>
<div>
    <el-form ref="formRef" :model="formData" :rules="formRule" label-width="200px" >
      <div class="gray-box">
        <title-more title="用户"></title-more>
        <div style="max-width: 1000px;">
          <el-form-item label="直属上级能拿到的佣金" prop="title">
            <div style="width: 100%">
              <div class="flexs">
                <el-input v-model.trim="formData.title" clearable placeholder="" style="width: 200px">
                  <template #append>元</template>
                </el-input>
                <div style="margin: 0 15px">或</div>
                <el-input v-model.trim="formData.title" clearable placeholder="" style="width: 200px">
                  <template #append>%</template>
                </el-input>
                <div style="flex: 1"></div>
              </div>
              <div>金额和比例都为0.00或空表示采用 用户等级或 系统设置的提成比例计算佣金</div>
            </div>
          </el-form-item>
          <el-form-item label="间接上级能拿到的佣金" prop="title">
            <div style="width: 100%">
              <div class="flexs">
                <el-input v-model.trim="formData.title" clearable placeholder="" style="width: 200px">
                  <template #append>元</template>
                </el-input>
                <div style="margin: 0 15px">或</div>
                <el-input v-model.trim="formData.title" clearable placeholder="" style="width: 200px">
                  <template #append>%</template>
                </el-input>
                <div style="flex: 1"></div>
              </div>
              <div>金额和比例都为0.00或空表示采用 用户等级或 系统设置的提成比例计算佣金</div>
            </div>
          </el-form-item>


          <el-form-item label="用户返佣" prop="type" required>
            <el-radio-group v-model="formData.type">
              <el-radio :value="1">开启</el-radio>
              <el-radio :value="2">关闭</el-radio>
            </el-radio-group>
            <span style="margin-left: 50px">关闭后，将不给用户返佣。</span>
          </el-form-item>
        </div>


      </div>


    </el-form>
</div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
import { UploadFilled, CloseBold } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import BaseSteps from "@components/BaseSteps.vue";
import TitleMore from "@components/title-more.vue";

const router = useRouter()
const { proxy } = getCurrentInstance()

onMounted(() => {
  // getClass()
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  insertFns.value = null
  if (editor == null) return
  editor.destroy()
})

/**
 * 添加
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} classType 弹窗类型，1是添加，2是编辑
 * @property {Array} formRef 表单规则
 * @property {Object} formData  表单字段
 * @property {Object} formRule  表单提示
 * @property {Function} submitNewsForm 提交表单
 */
const form_loading = ref(false)
const formRef = ref(null)
const formData = reactive({
  sub_cate_id: null,
  cate_id: "",
  title: "",
  dates: "",
  sort: "100",
  news_status: 0, // [0:显示,1:隐藏]
  audit: 1, // 0:待审核,1:已通过
  img_paths: "",
})
const formRule = reactive({
  cate_id: [{ required: true, message: "请选择文章分类", trigger: "change" }],
  title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
  img_paths: [{ required: true, message: "请选择封面图片", trigger: "blur" }],
  dates: [{ required: true, message: "请选择发布时间", trigger: "change" }],
  sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
})
const submitNewsForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let htmls = ""
      if (valueHtml.value) {
        htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
      }

      let cid = ""
      cid = Array.isArray(formData.cate_id) ? formData.cate_id[formData.cate_id.length - 1] : formData.cate_id
      form_loading.value = true
      proxy.$axios
          .post("article/add", {
            cate_id: cid,
            title: proxy.$util.replaceStr(formData.title),
            thumb: formData.img_paths,
            on_time: formData.dates,
            order_by: formData.sort,
            hidden: formData.news_status,
            audit: formData.audit,
            content: htmls,
          })
          .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
              proxy.$message({ message: "添加成功！", type: "success" })
              router.push("/News/NewsList")
            } else {
              proxy.$message({ message: res.data.msg, type: "error" })
            }
          })
          .catch((err) => {
            form_loading.value = false
          })
    }
  })
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Number} img_type 1是上传封面，2是富文本上传
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const img_type = ref(1)
const srcList = ref([])
const selectImg = (val) => {
  showImg.value = false
  if (img_type.value == 1) {
    formData.img_paths = val[0].photo
    srcList.value.push(proxy.imgUrl + val[0].photo)
  } else {
    for (let i = 0; i < val.length; i++) {
      insertFns.value(proxy.imgUrl + val[i].photo)
    }
  }
}
const delImg = () => {
  formData.img_paths = ""
  srcList.value = []
}
// 上传封面图
const clickCover = () => {
  img_type.value = 1
  showImg.value = true
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref("") // 内容 HTML
const toolbarConfig = {
  // 排除不需要的菜单"group-video",
  excludeKeys: ["insertLink", "insertImage", "editImage", "insertVideo", "viewImageLink", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 自定义上传图片
const insertFns = ref(null)
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义选择上传图片方式-可用于点击上传-图片库-选择图片插入
  customBrowseAndUpload(insertFn) {
    img_type.value = 2
    showImg.value = true
    insertFns.value = insertFn
  },
  // 不用图片库，直接上传图片
  // async customUpload(file, insertFn) {
  //     let data = new FormData()
  //     data.append("from", "article")
  //     data.append("image", file)
  //     proxy.$axios
  //         .post("upload/image", data)
  //         .then((res) => {
  //             if (res.data.code == 0) {
  //                 let url = proxy.imgUrl + res.data.data.path
  //                 insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
  //             } else {
  //                 proxy.$message({ message: res.data.msg, type: "error" })
  //             }
  //         })
  //         .catch((err) => {})
  // },
}
// 自定义上传视频
const videoLoading = ref(false)
editorConfig.MENU_CONF["uploadVideo"] = {
  async customUpload(file, insertFn) {
    videoLoading.value = true
    let data = new FormData()
    data.append("file", file)
    proxy.$axios
        .post("upload/video", data)
        .then((res) => {
          videoLoading.value = false
          if (res.data.code == 0) {
            let url = proxy.imgUrl + res.data.data.path
            insertFn(url) // 最后插入视频 insertFn(url poster)
          } else {
            proxy.$message({ message: res.data.msg, type: "error" })
          }
        })
        .catch((err) => {
          videoLoading.value = false
        })
  },
}

// 配置级联选择参数
const props = ref({
  value: "cate_id",
  label: "title",
  children: "children",
})
// 获取分类
const class_options = ref([])
function getClass() {
  proxy.$axios
      .get("article/add")
      .then((res) => {
        if (res.data.code == 0) {
          let result = res.data.data
          class_options.value = result
        } else {
          proxy.$message({ message: res.data.msg, type: "error" })
        }
      })
      .catch((err) => {})
}
</script>
<script>
export default {
  name: "commission",
}
</script>

<style lang="less" scoped>
.gray-box{
  background: #FCFCFC;
  border: 1px solid #E8E8E8;
  padding: 15px;
  margin-bottom: 15px;
}
</style>
